import os
import re
import subprocess
from pathlib import Path
from typing import Tuple, Optional

def detect_ubuntu() -> Tuple[Optional[str], Optional[str]]:
    """精准检测 Ubuntu 系统及版本，返回 (发行版名称, 版本号)"""
    # 方法 1: 通过 /etc/os-release 检测
    os_release = _parse_os_release()
    if os_release and os_release.get("ID") == "ubuntu":
        return "ubuntu", _normalize_version(os_release.get("VERSION_ID", ""))

    # 方法 2: 通过 lsb_release 命令检测
    lsb_info = _get_lsb_info()
    if lsb_info and lsb_info["ID"] == "Ubuntu":
        return "ubuntu", _normalize_version(lsb_info.get("Release", ""))

    # 方法 3: 检查遗留标识文件
    if _check_legacy_files():
        return "ubuntu", _get_legacy_version()

    return None, None  # 非 Ubuntu 系统

def _parse_os_release() -> dict:
    """解析 /etc/os-release 文件"""
    os_release_path = Path("/etc/os-release")
    if not os_release_path.exists():
        return {}

    os_info = {}
    with open(os_release_path, "r") as f:
        for line in f:
            line = line.strip()
            if line and "=" in line and not line.startswith("#"):
                key, value = line.split("=", 1)
                os_info[key] = value.strip('"')
    return os_info

def _get_lsb_info() -> dict:
    """通过 lsb_release 命令获取信息"""
    try:
        output = subprocess.check_output(
            ["lsb_release", "-a"], 
            stderr=subprocess.DEVNULL,
            text=True
        )
        lsb_info = {}
        for line in output.splitlines():
            if ":" in line:
                key, value = line.split(":", 1)
                lsb_info[key.strip()] = value.strip()
        return lsb_info
    except (subprocess.CalledProcessError, FileNotFoundError):
        return {}

def _check_legacy_files() -> bool:
    """检查 Ubuntu 遗留标识文件"""
    legacy_files = [
        "/etc/lsb-release",          # 标准 LSB 文件
        "/etc/debian_version",       # 部分容器镜像可能使用
        "/var/run/ubuntu-release"    # 某些定制系统
    ]
    return any(Path(f).exists() for f in legacy_files)

def _get_legacy_version() -> str:
    """从遗留文件中提取版本号"""
    # 尝试 /etc/lsb-release
    lsb_path = Path("/etc/lsb-release")
    if lsb_path.exists():
        with open(lsb_path, "r") as f:
            for line in f:
                if line.startswith("DISTRIB_RELEASE="):
                    version = line.split("=")[1].strip().strip('"')
                    return _normalize_version(version)
    
    # 尝试 /etc/debian_version (Ubuntu 基于 Debian)
    debian_version_path = Path("/etc/debian_version")
    if debian_version_path.exists():
        content = debian_version_path.read_text().strip()
        # Ubuntu 版本号可能以 "wheezy/sid" 形式存在
        if "/" in content:
            return _normalize_version(content.split("/")[0])
        return _normalize_version(content)
    
    return "unknown"

def _normalize_version(version: str) -> str:
    """规范化版本号格式 (e.g. '22.04 LTS' → '22.04')"""
    match = re.search(r"(\d+\.\d+)", version)
    if match:
        return match.group(1)
    return version.strip()

# 示例用法
if __name__ == "__main__":
    distro, version = detect_ubuntu()
    if distro:
        print(f"检测到系统: {distro} {version}")
    else:
        print("非 Ubuntu 系统")